package 力扣.链表.交换;

import java.util.List;

public class 旋转链表61 {
    /**
      让链表形成一个环，然后让倒数 k%len 个元素移动到链表最前面
     */
    public ListNode rotateRight(ListNode head, int k) {
        if (head == null || k == 0){
            return head;
        }
        ListNode dummy = head;
        int sum = 0;
//      遍历得到数组的长度
        while (head != null){
            sum++;
            head = head.next;
        }
        if (k % sum == 0){
            return dummy;
        }
//        倒数 ‘k % sum’个元素都需要放在链表的前面
        int te = (k % sum) + 1;

//        取链表位于倒数第 'k%sum + 1' 的节点
        ListNode fast = dummy;
        ListNode slow = dummy;
        while (fast != null && te-- > 1){
             fast = fast.next;
        }
        while (fast != null && fast.next !=null){
            fast = fast.next;
            slow = slow.next;
        }
        ListNode ans = slow.next;
        slow.next = null;
        fast.next = dummy;
        return ans;
    }
}
